<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const list = [
            { name: 'A', id: 1, parentId: 0 },
            { name: 'B', id: 2, parentId: 0 },
            { name: 'C', id: 3, parentId: 1 },
            { name: 'D', id: 4, parentId: 1 },
            { name: 'E', id: 5, parentId: 3 },
            { name: 'F', id: 6, parentId: 5 },
            { name: 'G', id: 7, parentId: 2 },
        ]

        // 数组转树
        function listToTree(list) {
            const result = []
            const map = new Map()

            // 先将所有数组元素存到map中
            for (let item of list) {
                map.set(item.id, { ...item, children: [] })
            }

            // 再遍历一次原数组
            for (let item of list) {
                if (map.has(item.parentId)) {
                    // 找得到父亲，则将当前元素放到父亲的children里
                    let parentItem = map.get(item.parentId)
                    let childrenItem = map.get(item.id)
                    parentItem.children.push(childrenItem)
                } else {
                    // 找不到，则放到结果数组里
                    result.push(map.get(item.id))
                }
            }

            return result
        }

        // 树转数组
        function treeToObjectArray(tree) {
            function dfs(list=[]){
                if(list&&list.length==0){
                    return
                }

                for(let node of list){
                    // 将当前节点放入结果数组中
                    let {name,id,parentId}=node
                    result.push({name,id,parentId})

                    // 递归
                    dfs(node.children)
                }
            }

            const result=[]
            dfs(tree)
            return result
        }

        let temp1=listToTree(list)
        console.log(temp1);
        let temp2=treeToObjectArray(temp1)
        console.log(temp2);
    </script>
</body>

</html>